#Requires AutoHotkey v2.0
#SingleInstance Force

js := "lev=function(){function r(r,t,e,o,h){return r<t||e<t?r>e?e+1:r+1:o===h?t:t+1}return function(t,e){if(t===e)return 0;if(t.length>e.length){var o=t;t=e,e=o}for(var h=t.length,n=e.length;h>0&&t.charCodeAt(h-1)===e.charCodeAt(n-1);)h--,n--;for(var a=0;a<h&&t.charCodeAt(a)===e.charCodeAt(a);)a++;if(n-=a,0===(h-=a)||n<3)return n;var c,f,d,u,A,C,i,l,v,g,p,s,b=0,j=[];for(c=0;c<h;c++)j.push(c+1),j.push(t.charCodeAt(a+c));for(var k=j.length-1;b<n-3;)for(v=e.charCodeAt(a+(f=b)),g=e.charCodeAt(a+(d=b+1)),p=e.charCodeAt(a+(u=b+2)),s=e.charCodeAt(a+(A=b+3)),C=b+=4,c=0;c<k;c+=2)f=r(i=j[c],f,d,v,l=j[c+1]),d=r(f,d,u,g,l),u=r(d,u,A,p,l),C=r(u,A,C,s,l),j[c]=C,A=u,u=d,d=f,f=i;for(;b<n;)for(v=e.charCodeAt(a+(f=b)),C=++b,c=0;c<k;c+=2)i=j[c],j[c]=C=r(i,f,C,v,j[c+1]),f=i;return C}}();"

GetData() {
  t := FileRead(A_ScriptDir "\数据.txt", "UTF-8")
  return StrSplit(Trim(t, " `t`r`n"), "`n", " `t`r")
}

Enter::
{
  w := WinGetID("A")
  static lst := GetData()
  MyGui := Gui("+AlwaysOnTop")
  MyGui.SetFont("s16")
  MyGui.MarginX := 0
  MyGui.MarginY := 0
  ED := MyGui.Add("Edit", "w200")
  ED.OnEvent("Change", ED_Change)
  LB := MyGui.Add("ListBox", "r20 w200")
  LB.OnEvent("Change", LB_Change)
  HotIfWinActive "ahk_id " MyGui.Hwnd
  Hotkey "Tab", MyGui_Key
  Hotkey "Enter", MyGui_Key
  HotIfWinActive
  for i in lst {
    LB.Add([i])
  }
  MyGui.OnEvent("Close", MyGui_Close)
  MyGui.Show

  MyGui_Close(*)
  {
    HotIfWinActive "ahk_id " MyGui.Hwnd
    Hotkey "Tab", "Off"
    Hotkey "Enter", "Off"
    HotIfWinActive
  }

  MyGui_Key(k)
  {
    if (k = "Tab") {
      if (LB.Value = ControlGetItems(LB).Length) {
        LB.Choose(1)
        A_Clipboard := ED.Text := LB.Text
      } else {
        LB.Choose(LB.Value + 1)
        A_Clipboard := ED.Text := LB.Text
      }
    }
    else if (k = "Enter") {
      WinActivate w
      WinWaitActive w
      SendText LB.Text
      SendEvent "{Enter}"
      WinClose MyGui
    }
  }

  ED_Change(*) {
    SetTimer After400, -400
  }

  LB_Change(*) {
    A_Clipboard := ED.Text := LB.Text
  }

  After400() {
    static hf := ComObject("htmlfile")
    hf.parentWindow.execScript(js)
    m := Map()
    for i in lst {
      m[i] := hf.parentWindow.lev(ED.Text, i) / (StrLen(ED.Text) + StrLen(i))
    }
    loop lst.Length - 1 {
      loop lst.Length - A_Index {
        if m[lst[A_Index]] > m[lst[A_Index + 1]] {
          t := lst[A_Index]
          lst[A_Index] := lst[A_Index + 1]
          lst[A_Index + 1] := t
        }
      }
    }
    LB.Opt("-Redraw")
    LB.Delete
    for i in lst {
      LB.Add([i])
    }
    LB.Opt("+Redraw")
    LB.Choose(1)
  }
}